from django.http import JsonResponse
from django.shortcuts import render
from thickcharts.models import Device

# 获取网关列表
from utils.utils import querylist_to_list, query_to_list

# 获取网关列表
def get_gateways(request):
    if request.method == 'GET':
        gateways = list(Device.objects.order_by('gateway').values_list('gateway', flat=True).distinct())
        res = {
            'data': {'gateways': gateways},
            'meta': {'status': 200, 'message': '获取网关列表成功'}
        }
    else:
        res = {
            'data': {'gateways': []},
            'meta': {'status': 401, 'message': '获取网关列表失败，请发送get请求'}
        }
    return JsonResponse(res)


# 获取devices列表
def get_devices(request):
    if request.method == 'GET':
        gateway = request.GET.get('gateway')
        if gateway:
            devices_query = Device.objects.filter(gateway=gateway).order_by('devicename').values_list('devicename', flat=True).distinct()
            devices = list(devices_query)
            res = {
                'data': {'devices': devices},
                'meta': {'status': 200, 'message': '获取设备列表成功'}
            }
        else:
            res = {
                'data': {'devices': []},
                'meta': {'status': 401, 'message': '获取设备列表失败，请指定网关'}
            }
    else:
        res = {
            'data': {'devices': []},
            'meta': {'status': 402, 'message': '获取设备列表失败，请发送get请求'}
        }
    return JsonResponse(res)

# 获取probe列表
def get_probes(request):
    if request.method == 'GET':
        gateway = request.GET.get('gateway')
        devicename = request.GET.get('devicename')
        if gateway and devicename:
            probes_query = Device.objects.filter(gateway=gateway, devicename=devicename).order_by('probe').values_list("probe", flat=True).distinct()
            probes = list(probes_query)
            res = {
                "data": {"probes": probes},
                "meta": {"status": 200, "message": "获取探头列表成功！"}
            }
        else:
            res = {
                "data": {"probes": []},
                "meta": {"status": 401, "message": "获取探头列表失败，请指定网关和设备名字"}
            }
    else:
        res = {
                "data": {"probes": []},
                "meta": {"status": 402, "message": "获取探头列表失败，请发起get请求！"}
            }
    return JsonResponse(res)

# 获取welcome页面饼状图需要的设备数量和在线设备数
def probe_count(request):
    if request.method == 'GET':
        all_devices = Device.objects.all().order_by('probe').values('probe', 'is_active').distinct()
        total = all_devices.count()
        online = all_devices.filter(is_active=True).count()
        offline = total - online
        count_list = [
            {'value': online, 'name': 'online'},
            {'value': offline, 'name': 'offline'}
        ]
        res = {
            'meta': {'status': 200, 'message': '获取设备数量统计数据成功'},
            'data': {'total': total, 'online': online, 'offline': offline, 'count_list': count_list}
        }
        return JsonResponse(res)